package com.js.statemachine.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.state.State;
import org.springframework.stereotype.Component;

/**
 * @author ：js
 * @date ：Created in 2021-03-09 13:35
 * @description: 状态机监听器
 * @version: 1.0
 */
@Component
@Slf4j
public class StateMachineEventListener extends StateMachineListenerAdapter<String, String> {

    /**
     * 状态机出错
     */
    @Override
    public void stateMachineError(StateMachine<String, String> stateMachine, Exception exception) {
        String state = stateMachine.getState().getId();
        log.error("状态机出错!,错误信息为:" + exception.getMessage());
        log.error("状态机当前的状态为;" + state);
    }

    /**
     * 状态改变
     *
     * @param from
     * @param to
     */
    @Override
    public void stateChanged(State<String, String> from, State<String, String> to) {
        if (from == null && to == null) {
            log.info("状态机出问题啦,没有找到该事件的对应状态转移情况!");
        }
//        if (from == null && to != null) {
//            log.info("现在状态机在{}状态", to.getId());
//        }
        if (from != null && to != null) {
            log.info("现在状态机从{}跳转到{}", from.getId(), to.getId());
        }
        if (from != null && to == null) {
            log.info("现在状态机从{}跳转到未知", from.getId());
        }
    }

    /**
     * 事件不接收
     *
     * @param event
     */
    @Override
    public void eventNotAccepted(Message<String> event) {
        log.info("当前状态不能接收{}事件!", event.getPayload());
    }
}
